<template>
  <div class="procurement-dashboard">
    <!-- 欢迎头部 -->
    <div class="welcome-header">
      <div class="welcome-content">
        <h1 class="welcome-title">
          采购管理仪表板
        </h1>
        <p class="welcome-desc">
          欢迎使用采购管理系统，这里为您提供全面的采购业务概览
        </p>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <el-row :gutter="16" class="metrics-row">
      <el-col :xs="24" :sm="12" :md="6">
        <MetricCard 
          title="供应商总数"
          :value="metrics.totalSuppliers"
          icon="OfficeBuilding"
          color="#1890ff"
          :trend="metrics.supplierTrend"
        >
          <template #footer>
            <span class="metric-footer">
              <el-icon><ArrowUp /></el-icon>
              较昨日 {{ metrics.supplierTrend > 0 ? '+' : '' }}{{ metrics.supplierTrend }}%
            </span>
          </template>
        </MetricCard>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <MetricCard 
          title="采购订单数"
          :value="metrics.totalOrders"
          icon="Document"
          color="#52c41a"
          :trend="metrics.orderTrend"
        >
          <template #footer>
            <span class="metric-footer">
              本月: {{ metrics.monthlyOrders }}
            </span>
          </template>
        </MetricCard>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <MetricCard 
          title="待处理订单"
          :value="metrics.pendingOrders"
          icon="Clock"
          color="#fa8c16"
          :trend="metrics.pendingTrend"
        >
          <template #footer>
            <span class="metric-footer">
              总金额: ¥{{ formatCurrency(metrics.pendingAmount) }}
            </span>
          </template>
        </MetricCard>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <MetricCard 
          title="采购总额"
          :value="metrics.totalAmount"
          suffix="万"
          icon="Money"
          color="#722ed1"
          :trend="metrics.amountTrend"
        >
          <template #footer>
            <span class="metric-footer">
              <el-progress 
                :percentage="metrics.amountRate" 
                :show-text="false"
                :stroke-width="4"
                color="#722ed1"
              />
            </span>
          </template>
        </MetricCard>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：图表和洞察 -->
      <div class="content-left">
        <!-- 采购趋势图表 -->
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">采购趋势分析</span>
              <el-radio-group v-model="trendPeriod" size="small">
                <el-radio-button value="7d">近7天</el-radio-button>
                <el-radio-button value="30d">近30天</el-radio-button>
                <el-radio-button value="90d">近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-placeholder">
            <el-empty description="采购趋势图表占位符" />
          </div>
        </el-card>

        <!-- 智能提醒 -->
        <el-card class="alert-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Bell /></el-icon>
                智能提醒
              </span>
              <el-button type="primary" text :icon="Refresh" @click="refreshAlerts">
                刷新
              </el-button>
            </div>
          </template>
          <PurchaseSmartAlerts 
            :purchase-records="[]"
            :loading="alertLoading"
            @alert-click="handleAlertClick"
          />
        </el-card>
      </div>

      <!-- 右侧：供应商和订单 -->
      <div class="content-right">
        <!-- 重要供应商 -->
        <el-card class="supplier-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">重要供应商</span>
              <el-button type="primary" text @click="gotoSuppliers">
                查看全部
              </el-button>
            </div>
          </template>
          <div class="supplier-list">
            <div 
              v-for="supplier in keySuppliers" 
              :key="supplier.id"
              class="supplier-item"
              @click="viewSupplier(supplier)"
            >
              <div class="supplier-info">
                <div class="supplier-name">{{ supplier.name }}</div>
                <div class="supplier-stats">
                  <span>订单: {{ supplier.orderCount }}</span>
                  <span>金额: ¥{{ formatCurrency(supplier.totalAmount) }}</span>
                </div>
              </div>
              <div class="supplier-rating">
                <el-rate
                  :model-value="Number(supplier.rating)"
                  :max="5"
                  disabled
                  allow-half
                  size="small"
                />
              </div>
            </div>
          </div>
        </el-card>

        <!-- 最近采购订单 -->
        <el-card class="order-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">最近采购订单</span>
              <el-button type="primary" text @click="gotoOrders">
                查看全部
              </el-button>
            </div>
          </template>
          <div class="order-list">
            <div 
              v-for="order in recentOrders" 
              :key="order.id"
              class="order-item"
              @click="viewOrder(order)"
            >
              <div class="order-info">
                <div class="order-number">{{ order.orderNumber }}</div>
                <div class="order-supplier">{{ order.supplierName }}</div>
              </div>
              <div class="order-amount">¥{{ formatCurrency(order.totalAmount) }}</div>
              <div class="order-status">
                <el-tag :type="getOrderStatusType(order.status)">
                  {{ getOrderStatusText(order.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { 
  OfficeBuilding, Document, Clock, Money, 
  Bell, Refresh, ArrowUp 
} from '@element-plus/icons-vue'
import MetricCard from '@/views/dashboard/components/MetricCard.vue'
import PurchaseSmartAlerts from './components/PurchaseSmartAlerts.vue'

// Router
const router = useRouter()

// 响应式数据
const trendPeriod = ref('30d')
const alertLoading = ref(false)

// 数据
const metrics = reactive({
  totalSuppliers: 42,
  totalOrders: 128,
  pendingOrders: 24,
  totalAmount: 285,
  supplierTrend: 5.2,
  orderTrend: 3.8,
  pendingTrend: -2.1,
  amountTrend: 1.5,
  monthlyOrders: 36,
  pendingAmount: 125000,
  amountRate: 88
})

const smartAlerts = ref([
  {
    id: '1',
    type: 'risk',
    title: '供应商风险预警',
    description: '供应商A评分下降，建议关注',
    priority: 'high'
  },
  {
    id: '2',
    type: 'opportunity',
    title: '采购机会',
    description: '供应商B提供新品优惠',
    priority: 'medium'
  },
  {
    id: '3',
    type: 'performance',
    title: '订单提醒',
    description: '3个订单即将到期',
    priority: 'low'
  }
])

const keySuppliers = ref([
  {
    id: 1,
    name: '供应商A',
    orderCount: 24,
    totalAmount: 1250000,
    rating: 4.5
  },
  {
    id: 2,
    name: '供应商B',
    orderCount: 18,
    totalAmount: 980000,
    rating: 4.2
  },
  {
    id: 3,
    name: '供应商C',
    orderCount: 15,
    totalAmount: 760000,
    rating: 4.8
  }
])

const recentOrders = ref([
  {
    id: 1001,
    orderNumber: 'PO202501001',
    supplierName: '供应商A',
    totalAmount: 125000,
    status: 'pending'
  },
  {
    id: 1002,
    orderNumber: 'PO202501002',
    supplierName: '供应商B',
    totalAmount: 85000,
    status: 'shipped'
  },
  {
    id: 1003,
    orderNumber: 'PO202501003',
    supplierName: '供应商C',
    totalAmount: 65000,
    status: 'completed'
  }
])

// 方法
const refreshAlerts = () => {
  alertLoading.value = true
  setTimeout(() => {
    alertLoading.value = false
  }, 1000)
}

const gotoSuppliers = () => {
  router.push('/procurement/suppliers')
}

const gotoOrders = () => {
  router.push('/procurement/orders')
}

const viewSupplier = (supplier: any) => {
  console.log('查看供应商:', supplier)
}

const viewOrder = (order: any) => {
  console.log('查看订单:', order)
}

const handleAlertClick = (alert: any) => {
  console.log('处理提醒:', alert)
}

const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, any> = {
    pending: 'warning',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 生命周期
onMounted(() => {
  // 加载数据
  console.log('采购仪表板已加载')
})
</script>

<style scoped lang="scss">
.procurement-dashboard {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
  
  .welcome-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .welcome-content {
      .welcome-title {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
      }
      
      .welcome-desc {
        margin: 0;
        font-size: 16px;
        opacity: 0.9;
      }
    }
  }
  
  .metrics-row {
    margin-bottom: 24px;
  }
  
  .main-content {
    display: grid;
    grid-template-columns: 1fr 400px;
    gap: 24px;
    margin-bottom: 24px;
    
    .content-left {
      display: flex;
      flex-direction: column;
      gap: 24px;
    }
    
    .content-right {
      display: flex;
      flex-direction: column;
      gap: 24px;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .card-title {
        font-size: 16px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 6px;
      }
    }
    
    .chart-placeholder {
      height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .supplier-list {
      .supplier-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background-color 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &:last-child {
          border-bottom: none;
        }
        
        .supplier-info {
          flex: 1;
          
          .supplier-name {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .supplier-stats {
            font-size: 12px;
            color: #606266;
            
            span {
              margin-right: 12px;
            }
          }
        }
        
        .supplier-rating {
          margin-left: 12px;
        }
      }
    }
    
    .order-list {
      .order-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background-color 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &:last-child {
          border-bottom: none;
        }
        
        .order-info {
          flex: 1;
          
          .order-number {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .order-supplier {
            font-size: 12px;
            color: #606266;
          }
        }
        
        .order-amount {
          font-weight: 500;
          margin: 0 12px;
        }
      }
    }
  }
  
  .metric-footer {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #909399;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .procurement-dashboard {
    .main-content {
      grid-template-columns: 1fr;
      
      .content-right {
        order: -1;
      }
    }
  }
}

@media (max-width: 768px) {
  .procurement-dashboard {
    padding: 16px;
    
    .welcome-header {
      flex-direction: column;
      gap: 16px;
      text-align: center;
    }
    
    .main-content {
      gap: 16px;
    }
  }
}
</style>